﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;

namespace TrafficWatcher.ViewModels.Helpers
{
    public class WindowServiceImpl : IWindowService
    {
        private readonly IList<Window> windows = new List<Window>();

        public void OpenWindow(Type t)
        {
            if (windows.FirstOrDefault(w => w.GetType() == t) == null)
            {
                var window = (Window) Activator.CreateInstance(t);
                window.Unloaded += WindowUnloaded;
                window.Show();
                windows.Add(window);
            }
        }

        public void CloseWindow(Type t)
        {
            var window = windows.FirstOrDefault(w => w.GetType() == t);
            if (window != null)
            {
                window.Close();
            }
        }

        private void WindowUnloaded(object sender, RoutedEventArgs e)
        {
            var window = (Window)sender;
            window.Unloaded -= WindowUnloaded;
            windows.Remove(window);
        }
    }
}